package com.hui.security.config;

import com.hui.security.common.jwt.JwtToken;
import com.hui.security.common.jwt.JwtUtil;
import com.hui.security.sys.entity.Permission;
import com.hui.security.sys.entity.Role;
import com.hui.security.sys.entity.User;
import com.hui.security.sys.exception.ExceptionEnum;
import com.hui.security.sys.exception.HSecurityException;
import com.hui.security.sys.service.PermissionService;
import com.hui.security.sys.service.RoleService;
import com.hui.security.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <b><code>UserRealm</code></b>
 * <p/>
 * Description: shiro 领域定义
 * <p/>
 * <b>Creation Time:</b> 2019/1/5 14:27.
 *
 * @author HuWeihui
 */
@Component
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }


    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        if (!(authenticationToken instanceof JwtToken)){
            throw new HSecurityException("token无效");
        }
        String userToken = (String) authenticationToken.getCredentials();
        if (StringUtils.isEmpty(userToken)){
            throw new HSecurityException("token无效");
        }
        //获取用户账号
        String userAccount = JwtUtil.getUserAccount(userToken);

        //获取用户信息
        User user = userService.getByUserAccount(userAccount);

        if (null == user) {
            throw new HSecurityException(ExceptionEnum.SECURITY_ERROR_USER_NOT_EXIST);
        }

        if (!JwtUtil.verify(userToken, user.getUserAccount(), user.getUserPassword())) {
            throw new HSecurityException(ExceptionEnum.SECURITY_ERROR_PASSWORD_INCORRECT);
        }
//        return new SimpleAuthenticationInfo(user.getUserAccount(),
//                user.getUserPassword(),
//                ByteSource.Util.bytes(user.getUserAccount()),
//                getName());
        return new SimpleAuthenticationInfo(userToken, userToken, getName());
    }

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String userToken = principalCollection.toString();
        if (StringUtils.isEmpty(userToken)){
            throw new HSecurityException(ExceptionEnum.SECURITY_ERROR_FORBID_ACCESS);
        }
        String userAccount = JwtUtil.getUserAccount(userToken);
        //获取用户
        User user = userService.getByUserAccount(userAccount);
        List<Role> roleList = roleService.listByUserId(user.getUserId());
        //添加角色和权限
        for (Role role : roleList) {
            authorizationInfo.addRole(role.getRoleName());
            List<Permission> permissionList = permissionService.listByRoleId(role.getRoleId());
            for (Permission permission : permissionList) {
                authorizationInfo.addStringPermission(permission.getResourceUrl());
            }
        }
        return authorizationInfo;
    }

}
